package com.md.notes.fragment;

import android.app.AlertDialog;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.util.Log;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.activity.OnBackPressedCallback;
import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.md.notes.MainActivity;
import com.md.notes.R;
import com.md.notes.model.db.service.DaoService;
import com.md.notes.model.entity.Note;
import com.md.notes.model.module.log.LoggerABC;
import com.md.notes.model.module.log.LoggerBuilder;
import com.md.notes.model.module.string.StrBuffer;
import com.md.notes.util.CheckUtils;
import com.md.notes.util.DateUtils;
import com.md.notes.util.StringUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * A simple {@link Fragment} subclass.
 * Use the {@link EditFragment#newInstance} factory method to
 * create an instance of this fragment.
 *
 * 编辑页面
 */
public class EditFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    public static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());

    private EditText editText;
    private Button btnSave;
    private ImageButton btnTable;
    private ImageButton btnLink;
    private ImageButton btnTime;

    private DaoService daoService;

    public EditFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment EditFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static EditFragment newInstance(String param1, String param2) {
        EditFragment fragment = new EditFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

        daoService = new DaoService(getContext());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_edit, container, false);
        editText = view.findViewById(R.id.editor);
        btnSave = view.findViewById(R.id.btn_save);
        btnTable = view.findViewById(R.id.btn_table);
        btnLink = view.findViewById(R.id.btn_link);
        btnTime = view.findViewById(R.id.btn_time);
        LoggerABC loggerABC = LoggerBuilder.build(requireActivity());
        loggerABC.logMessage(LoggerABC.INFO,"EditFragment onCreateView：mParam1"+mParam1);

        String markdown = mParam1;
        if(CheckUtils.checkIsNull(markdown)){
            markdown = initNote();
        }
        editText.setText(markdown);

        addListenr();
        return view;
    }

    private void addListenr() {
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*if (permissionModel.checkAndRequestPermissions(requireActivity())) {
                }*/
                saveMarkdownFile();
                // 如果没有权限，会通过之前设置的 callback 在获取权限后自动调用保存
            }
        });
        // 注册返回键处理
        requireActivity().getOnBackPressedDispatcher().addCallback(
                getViewLifecycleOwner(), // LifecycleOwner会自动处理生命周期
                new OnBackPressedCallback(true) {
                    @Override
                    public void handleOnBackPressed() {
                        /*if (hasUnsavedChanges()) {
                        showExitConfirmDialog();
                        } else {
                        }*/
                        // 没有未保存的更改，直接返回
                        //setEnabled(false);
                        //requireActivity().getOnBackPressedDispatcher().onBackPressed();
                        // 设置结果并返回
                        finishWithResult();  // 调用这个方法
                    }
                }
        );
        btnTable.setOnClickListener((v)->{
            //获取光标位置
            int cursorPosition = editText.getSelectionStart();
            //创建Editable对象
            Editable editable = editText.getText();
            //在光标位置插入表格模板
            String tableTemplate = "\n| 表头1 | 表头2 | 表头3 |\n|:-------:|:-------:|:-------:|\n| 内容1 | 内容2 | 内容3 |\n";
            editable.insert(cursorPosition, tableTemplate);
        });
        btnLink.setOnClickListener((v)->{
            //获取光标位置
            int cursorPosition = editText.getSelectionStart();
            //创建Editable对象
            Editable editable = editText.getText();
            //在光标位置插入表格模板
            String tableTemplate = "\n[]()\n";
            editable.insert(cursorPosition, tableTemplate);
        });

        btnTime.setOnClickListener((v)->{
            //获取光标位置
            int cursorPosition = editText.getSelectionStart();
            //创建Editable对象
            Editable editable = editText.getText();
            //在光标位置插入表格模板
            String dateTime = String.format("%s", DateUtils.getCurrentDateSSS());
            editable.insert(cursorPosition, dateTime);
        });
    }

    private void finishWithResult() {
        requireActivity().setResult(requireActivity().RESULT_OK);
        requireActivity().finish();
    }
    /**
     * 保存 Markdown 文件到本地
     */
    private void saveMarkdownFile() {
        LoggerABC loggerABC = LoggerBuilder.build(requireActivity());
        try {
            // 获取外部存储根目录
            File rootDir = Environment.getExternalStorageDirectory();
            // 创建 MdNotes 文件夹
            File mdNotesDir = new File(rootDir, "MdNotes");
            if (!mdNotesDir.exists()) {
                if (!mdNotesDir.mkdirs()) {
                    Toast.makeText(requireContext(), "创建目录失败", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            String content = getEditContent();
            String head = StringUtils.extractBetweenDashes(content);
            Note note = Note.parseFromString(head);

            //创建图片文件夹
            File mdSpecNoDir = new File(mdNotesDir, note.getSpecNo());
            if (!mdSpecNoDir.exists()) {
                if (!mdSpecNoDir.mkdirs()) {
                    Toast.makeText(requireContext(), "创建目录失败"+note.getSpecNo(), Toast.LENGTH_SHORT).show();
                    return;
                }
            }

            // 生成文件名（使用时间戳）
            //String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
            StrBuffer strBuffer = new StrBuffer();
            strBuffer.append("Note_");
            strBuffer.append(note.getSpecNo());
            strBuffer.append("_");
            strBuffer.append(note.getAppNo());
            strBuffer.append(".md");
            String fileName = strBuffer.toString();
            File noteFile = new File(mdNotesDir, fileName);

            // 使用 UTF-8 编码写入文件
            try (OutputStreamWriter writer = new OutputStreamWriter(
                    new FileOutputStream(noteFile), StandardCharsets.UTF_8)) {
                writer.write(content);
                writer.flush();
                Toast.makeText(requireContext(), "保存成功：" + noteFile.getAbsolutePath(), 
                        Toast.LENGTH_SHORT).show();
            }
            note.setContent(content);
            daoService.updateNote(note);
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(requireContext(), "保存失败：" + e.getMessage(), 
                    Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    @MainThread
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {


    }

    public String getEditContent() {
        return editText.getText().toString();
    }

    private String initNote() {
        LoggerABC loggerABC = LoggerBuilder.build(requireActivity());
        try {
            // 读取模板文件
            AssetManager assetManager = requireActivity().getAssets();
            InputStream inputStream = assetManager.open("note_template.ftl");
            String template = new BufferedReader(new InputStreamReader(inputStream))
                    .lines()
                    .collect(Collectors.joining("\n"));
            
            // 获取当前日期和时间
            //SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            //Date now = new Date();
            
            // 手动替换变量
            return template.replace("${appNo}", timeStamp)
                          .replace("${currentDate}", DateUtils.getCurrentDateSSS());
            
        } catch (IOException e) {
            loggerABC.setException(e);
            loggerABC.logMessage(LoggerABC.ERROR,"Error occurred during initNote: " + e.getMessage());
            Log.e("EditFragment", "模板处理失败", e);
            //Toast.makeText(requireContext(), "初始化笔记失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
            return "";
        }
    }

    private void showExitConfirmDialog() {
        new AlertDialog.Builder(requireContext())
                .setTitle("提示")
                .setMessage("有未保存的更改，确定要退出吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    requireActivity().finish();
                })
                .setNegativeButton("取消", null)
                .setNeutralButton("保存并退出", (dialog, which) -> {
                    saveMarkdownFile();
                    requireActivity().finish();
                })
                .show();
    }

}